<?php

include('config.php');

if (!base_obj::security(array('admin', 'client', 'technic'))) {
    header("Location:" . ROOT);
    exit;
}

$tables = array(
    'list_of_tasks',
    'state_of_cash',
    'timesheets'
);

if (!in_array($_REQUEST['table'], $tables)) {
    header("Location:" . ROOT);
    exit;
}

if (isset($_SESSION['debug_mode']) && ($_SESSION['debug_mode'])) {
    base_obj::showDebug();
}

$output_data = array();

switch ($_REQUEST['table']) {
    case 'list_of_tasks':
        $name = 'List of tasks';
        $file = 'list_of_tasks';
        $task_obj = new task_obj();

        $filter = $_SESSION['list_of_tasks_filter'];

        if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) {
            $filter['clients'] = $_SESSION['user']['clients'];
        }

        if (isset($_SESSION['list_of_tasks_fulltext']) && !empty($_SESSION['list_of_tasks_fulltext'])) {
            $tasks = $task_obj->getListOfTasksByFulltext($_SESSION['list_of_tasks_fulltext'], $filter, $_SESSION['list_of_tasks_order']);
        } else {
            $tasks = $task_obj->getListOfTasks($filter, $_SESSION['list_of_tasks_order']);
        }

        $client_obj = new client_obj();
        $user_obj = new user_obj();
        foreach ($tasks as $key => $task) {

            $tasks[$key]['created'] = base_obj::convertDateTo($task['created'], 'dd/mm/yyyy', 'date');
            $client = $client_obj->getClient($task['client']);
            $tasks[$key]['client'] = $client['fullName'];
            $user = $user_obj->getUserById($task['responsible']);
            $tasks[$key]['responsible'] = $user['name'] . ' ' . $user['surname'];
            if (!empty($task['worker'])) {
                $user = $user_obj->getUserById($task['worker']);
                $tasks[$key]['worker'] = $user['name'] . ' ' . $user['surname'];
            } else {
                $tasks[$key]['worker'] = '-';
            }
            $tasks[$key]['deadline'] = base_obj::convertDateTo($task['deadline'], 'dd/mm/yyyy', 'date');
            $type = $task_obj->getTaskType($task['type']);
            $tasks[$key]['type'] = $type['type_of_record'];
            $priority = $task_obj->getTaskPriority($task['priority']);
            $tasks[$key]['priority'] = $priority['Priorita'] . ' - ' . $priority['Popis'];
            $status = $task_obj->getTaskStatus($task['status']);
            $tasks[$key]['status'] = $status['stav'];
            unset($tasks[$key]['taskId']);
            unset($tasks[$key]['file']);
            if ($_SESSION['user']['user_type_id'] != USER_TYPE_ADMIN)
                unset($tasks[$key]['rate']);
            $user = $user_obj->getUserById($task['creator']);
            $tasks[$key]['creator'] = $user['name'] . ' ' . $user['surname'];
            if (!empty($task['updater'])) {
                $user = $user_obj->getUserById($task['updater']);
                $tasks[$key]['updater'] = $user['name'] . ' ' . $user['surname'];
            } else {
                $tasks[$key]['updater'] = '-';
            }
            $tasks[$key]['added'] = base_obj::convertDateTo($task['created'], 'dd/mm/yyyy H:i:s', 'datetime');
            $tasks[$key]['updated'] = base_obj::convertDateTo($task['created'], 'dd/mm/yyyy H:i:s', 'datetime');
            if (!empty($task['consult']))
                $tasks[$key]['consult'] = 'X';
            else
                $tasks[$key]['consult'] = '-';
            if (!empty($task['problem_type'])) {
                $problem = $task_obj->getTaskTypeOfProblem($task['problem_type']);
                $tasks[$key]['problem_type'] = $problem['problem'];
            } else {
                $tasks[$key]['problem_type'] = '-';
            }
        }

        $title = array(
            'title' => 'Title',
            'created' => 'Created',
            'client' => 'Client',
            'worker' => 'Worker',
            'responsible' => 'Responsible',
            'deadline' => 'Deadline',
            'type' => 'Task type',
            'priority' => 'Priority',
            'status' => 'Status',
            'creator' => 'Who created',
            'added' => 'When created',
            'updater' => 'Who updated',
            'updated' => 'When updated',
            'problem_type' => 'Type of problem',
            'consult' => 'Consult',
            'duration' => 'Expected amount',
            'rate' => '%'
        );

        $output_data = $tasks;
        break;
    case 'state_of_cash':
        $name = 'State_of_cash';
        $file = 'state_of_cash';
        $cash_obj = new cash_obj();

        $filter = $_SESSION['cash_filter'];

        if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_TECHNIC)
            $filter['user'] = $_SESSION['user']['user_id'];

        if (isset($_SESSION['cash_fulltext']) && !empty($_SESSION['cash_fulltext'])) {
            $cashes = $cash_obj->getListOfCashesByFulltext($_SESSION['cash_fulltext'], $filter, $_SESSION['cash_order']);
        } else {
            $cashes = $cash_obj->getListOfCashes($filter, $_SESSION['cash_order']);
        }

        $user_obj = new user_obj();
        foreach ($cashes as $key => $cash) {

            $cashes[$key]['created'] = base_obj::convertDateTo($cash['created'], 'dd/mm/yyyy H:i:s', 'datetime');
            $user = $user_obj->getUserById($cash['who_added']);
            $cashes[$key]['who_added'] = $user['name'] . ' ' . $user['surname'];
            $user = $user_obj->getUserById($cash['user']);
            $cashes[$key]['user'] = $user['name'] . ' ' . $user['surname'];
            $cashes[$key]['date'] = base_obj::convertDateTo($cash['date'], 'dd/mm/yyyy', 'date');
            $type = $cash_obj->getCashMoveTypeById($cash['type_of_move']);
            $cashes[$key]['type_of_move'] = $type['TypPohybu'];
            if (!empty($cash['s']))
                $cashes[$key]['s'] = 'X';
            else
                $cashes[$key]['s'] = '-';
            unset($cashes[$key]['Id']);
            unset($cashes[$key]['transfer_between']);
        }

        $title = array(
            'created' => 'Created',
            'who_added' => 'Who added',
            'user' => 'User',
            'date' => 'Date',
            'amount' => 'Amount',
            'type_of_move' => 'Type of move',
            'description' => 'Description',
            's' => 'S'
        );

        $output_data = $cashes;
        break;
    case 'timesheets':
        $name = 'TSDR';
        $file = 'tsdr';
        $record_obj = new record_obj();

        $filter = $_SESSION['timesheets_filter'];

        if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) {
            $filter['clients'] = $_SESSION['user']['clients'];
        }

        if (isset($_SESSION['timesheets_fulltext']) && !empty($_SESSION['timesheets_fulltext'])) {
            $records = $record_obj->getListOfRecordsByFulltext($_SESSION['timesheets_fulltext'], $filter, $_SESSION['timesheets_order']);
        } else {
            $records = $record_obj->getListOfRecords($filter, $_SESSION['timesheets_order']);
        }

        $client_obj = new client_obj();
        $user_obj = new user_obj();
        $tariff_obj = new tariff_obj();
        foreach ($records as $key => $record) {
            $records[$key]['date'] = base_obj::convertDateTo($record['date'], 'dd/mm/yyyy H:i:s', 'datetime');
            $client = $client_obj->getClient($record['client']);
            $records[$key]['client'] = $client['fullName'];
            $user = $user_obj->getUserById($record['user_id']);
            $records[$key]['user_id'] = $user['name'] . ' ' . $user['surname'];
            $type = $record_obj->getTypeOfRecordById($record['type']);
            $records[$key]['type'] = $type['type_of_record'];
            if ($record['tariff'] != -1) {
                $tariff = $tariff_obj->getTariffById($record['tariff']);
                $records[$key]['tariff'] = $tariff['title'];
            } else {
                $records[$key]['tariff'] = '-';
            }
            unset($records[$key]['recordId']);
            unset($records[$key]['taskId']);
            unset($records[$key]['after_hours']);
            unset($records[$key]['attention']);
        }

        $title = array(
            'date' => 'Date',
            'client' => 'Client',
            'user_id' => 'User',
            'type' => 'Type of record',
            'tariff' => 'Tariff',
            'amount' => 'Amount',
            'description' => 'Description',
            'unit_price' => 'Unit price'
        );

        $output_data = $records;
        break;
}

require_once PATH_TO_LIBRARY . 'excel_writer/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Alfa CM")
        ->setLastModifiedBy("Alfa CM")
        ->setTitle("Export: " . $name)
        ->setSubject("Export: " . $name)
        ->setDescription("Export: " . $name)
        ->setKeywords("Alfacentauri CM")
        ->setCategory("Export: " . $name);

foreach ($output_data as $row => $data) {
    $r = $row + 2;
    $l = 'A';
    foreach ($data as $key => $value) {
        if (!is_numeric($key)) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($l . $r, $value);
            $l++;
        }
    }
}

$l = 'A';
foreach ($output_data[0] as $key => $value) {
    if (!is_numeric($key)) {
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($l . 1, $title[$key]);
        $objPHPExcel->getActiveSheet()->getColumnDimension($l)->setWidth(30);
        $l++;
    }
}

// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

$export_path = FILE . "temp/";
if (!file_exists($export_path)) {
    mkdir($export_path, 0775, true);
    chmod($export_path, 0775);
}
$save_path = $export_path . $file . '.xls';

// ulozenie
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save($save_path);

Header('Content-Description: File Transfer');
Header('Content-Type: application/vnd.ms-excel');
Header('Content-Disposition: attachment; filename=' . $file . ".xls");
Header('Content-Transfer-Encoding: binary');
Header('Expires: 0');
Header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
Header('Pragma: public');
Header('Content-Length: ' . filesize($save_path));
ob_clean();
flush();
readfile($save_path);
unlink($save_path);
exit;
?>
